# -*- coding: utf-8 -*-
from django.contrib.auth.models import User
from django.contrib.contenttypes import generic
from django.contrib.contenttypes.models import ContentType
from django.db import models

class TagManager(models.Manager):
  def get_by_natural_key(self, category, type):
    return self.get(category=category, type=type)
    
class TagType(models.Model):
  category = models.CharField(max_length=256, db_index=True)
  type = models.CharField(max_length=256, db_index=True)
  
  class Meta:
    db_table = 'TagTypes'
    verbose_name_plural = "TagTypes"
    unique_together = (("category", "type",),)
  
  objects = TagManager()
  def natural_key(self):
    return (self.category, self.type, )

  def __unicode__(self):
    return self.category +' - '+ self.type


class TaggedObject(models.Model):
  user = models.ForeignKey(User)
  tag = models.ForeignKey(TagType)

  content_type = models.ForeignKey(ContentType)
  object_id = models.CharField(max_length=40, db_index=True)
  content_object = generic.GenericForeignKey()

  
  created = models.DateTimeField(db_index=True, auto_now_add=True)

  def __unicode__(self):
    return u"%s tagged %s - %s: %s" % (self.user, self.content_type, self.content_type, self.tag)

  class Meta:
    unique_together = (('tag', 'content_type', 'object_id', 'user'),)
    ordering = ('-created',)
